from sqlalchemy.orm import Session
from pathlib import Path
from ..models import File, User
from ..core import USER_STORAGE_PATH


# 创建文件
def create_file(db: Session, file_name, owner: User, file_content: bytes):
    db_file = File(file_name=file_name,
                   file_size=len(file_content),
                   folder_path=str(owner.id),
                   owner_id=owner.id)
    db.add(db_file)
    file_path = Path(USER_STORAGE_PATH, db_file.folder_path, db_file.file_name)
    if not file_path.parent.exists():
        file_path.parent.mkdir(parents=True)
    with open(file_path, "wb") as f:
        f.write(file_content)
    owner.disk_used += len(file_content)
    db.commit()
    db.refresh(db_file)
    return db_file


# 删除文件
def delete_file_by_name(db: Session, file_name: str, owner: User):
    file = db.query(File).filter_by(file_name=file_name, owner_id=owner.id).first()
    if file:
        file_path = Path(USER_STORAGE_PATH, file.folder_path, file.file_name)
        if file_path.exists():
            file_path.unlink()
        else:
            return False
        owner.disk_used -= file.file_size
        db.delete(file)
        db.commit()
        return True
    return False


# 读取用户的所有文件
def get_files_by_owner(db: Session, owner_id: int):
    return db.query(File).filter_by(owner_id=owner_id).all()


# 根据文件名读取文件信息
def get_file_by_name(db: Session, file_name: str, owner_id: int):
    return db.query(File).filter_by(file_name=file_name, owner_id=owner_id).first()


# 根据owner_id和文件名确定表中是否存在
def file_exists(db: Session, file_name: str, owner_id: int):
    return db.query(File).filter_by(file_name=file_name, owner_id=owner_id).first() is not None
